Skip to main content

Report Ghosting

After successfully encrypting the 'Report Ghosting' data, the next crucial step is to securely transmit this data to our server. This step involves crafting an HTTP POST request, including the encrypted data in the request body, and using your subscriptionKey for authentication.

Preparing the HTTP Request

  1. Endpoint URL: Obtain the specific URL of the server endpoint designed to receive the encrypted data. This URL will be provided as part of your API documentation or directly within your account on href: https://app.offerghosting.com.

  2. Headers:

    • Content-Type: Set this header to application/json to indicate the nature of the data being sent.
    • Authorization: Use this header to pass your subscriptionKey. The exact format may vary based on the server's requirements, but it typically follows a standard such as Bearer <your_subscriptionKey>.
  3. Request Body: Include the encrypted 'Report Ghosting' data as part of the request body. Depending on the API's design, this may involve embedding the encrypted data within a larger JSON structure or sending it directly as the body's content.

Example HTTP POST Request in Various Languages

JavaScript

tip

To execute a JavaScript file, it is advisable to install the Axios library, a popular choice for making HTTP requests in JavaScript environments.

Encryption Function

Create encryptData.js, This file contains the encryption function.

const crypto = require('crypto');

function encryptData(data, pluginKeyHex) {
const pluginKey = Buffer.from(pluginKeyHex, 'hex');
if (pluginKey.length !== 32) {
throw new Error("Key must be 32 bytes for AES-256-CBC");
}
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', pluginKey, iv);
let encryptedData = cipher.update(JSON.stringify(data), 'utf8', 'base64');
encryptedData += cipher.final('base64');

const encryptedBlob = Buffer.concat([iv, Buffer.from(encryptedData, 'base64')]).toString('base64');
return encryptedBlob;
}
module.exports = encryptData;

Sending encrypted data to the server

Create sendEncryptedData.js, This file contains the function to send encrypted data to the server.

const axios = require('axios');
function sendEncryptedData(encryptedData, apiUrl, subscriptionKey) {
const payload = {
encryptedData: encryptedData,
subscriptionKey: subscriptionKey
};
axios.post(apiUrl, payload, {
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
console.log("Debug: Response Status Code:", response.data);

if (response.data.message) {
console.log("API Message:", response.data.message);
} else {
console.log("No 'message' field in response.");
}
}).catch(error => {
console.error("Error occurred:", error.response ? error.response.data : error.message);
});
}
module.exports = sendEncryptedData;

Main code using both the function

Create index.js: This is the main file that uses both functions.

const encryptData = require('./encryptData');
const sendEncryptedData = require('./sendEncryptedData');

const testData = {
email: 'ADD_EMAIL',
governmentId: 'ADD_GOVERNMENT_ID',
governmentIdType: 'ADD_GOVERNMENT_ID_TYPE',
jobObject: {
jobSkills: 'ADD_JOB_SKILLS.split'(','),
jobRole: 'ADD_JOB_ROLE',
employmentType: 'ADD_EMPLOYMENT_TYPE',
ghostedReasonByCompany: 'ADD_GHOSTED_REASON_BY_COMPANY'
}
};

const pluginKey = 'ADD_YOUR_PLUGIN_KEY';
const subscriptionKey = 'ADD_YOUR_SUBSCRIPTION_KEY';
const apiUrl = 'ADD_API_URL';

try {
console.log("Starting Encryption Process");
const encryptedResult = encryptData(testData, pluginKey);

console.log("Sending Encrypted Data to API");
sendEncryptedData(encryptedResult, apiUrl, subscriptionKey);
} catch (e) {
console.error("An error occurred:", e.message);
}

Python

tip

Installation Steps

  • Ensure Python is Installed: Download and install the latest version of Python from the official Python website.
  • Verify Python Installation: Run the command python --version to confirm that Python is installed correctly.
  • Check pip Installation: Verify the installation of pip, the package installer for Python, by executing pip --version.
  • Install the cryptography Package: Use pip to install the cryptography package required for cryptographic operations: pip install cryptography.
  • Confirm Installation: Ensure the cryptography package is installed successfully with the command pip show cryptography.
  • Install the requests Library: Install the requests library, commonly used for making HTTP requests in Python applications: pip install requests.

Encryption Function

Create a file named encryption.py:

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import os, base64, json

def encrypt_data(data, plugin_key_hex):
plugin_key = bytes.fromhex(plugin_key_hex)
if len(plugin_key) != 32:
raise ValueError("Key must be 32 bytes for AES-256-CBC")

iv = os.urandom(16)
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(json.dumps(data).encode()) + padder.finalize()

cipher = Cipher(algorithms.AES(plugin_key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
encrypted_data = encryptor.update(padded_data) + encryptor.finalize()
encrypted_blob = base64.b64encode(iv + encrypted_data)
return encrypted_blob.decode()

Sending encrypted data to the server

Create a file named send_data.py:

import requests
def send_encrypted_data(encrypted_data, api_url, subscription_key):
headers = {'Content-Type': 'application/json'}
payload = {
"encryptedData": encrypted_data,
"subscriptionKey": subscription_key
}
response = requests.post(api_url, json=payload, headers=headers)

# Handle response
response_data = response.json()
if 'message' in response_data:
print("API Message:", response_data['message'])

return response

Main code using both the function

Create a file named main.py:

from dotenv import load_dotenv
import os
from encryption import encrypt_data
from send_data import send_encrypted_data

test_data = {
"email": 'ADD_EMAIL',
"governmentId": 'ADD_GOVERNMENT_ID',
"governmentIdType": 'ADD_GOVERNMENT_ID_TYPE',
"jobObject": {
"jobSkills": 'ADD_JOB_SKILLS'.split(','),
"jobRole": 'ADD_JOB_ROLE',
"employmentType": 'ADD_EMPLOYMENT_TYPE',
"ghostedReasonByCompany": 'ADD_GHOSTED_REASON_BY_COMPANY'
}
}

plugin_key_hex = 'ADD_YOUR_PLUGIN_KEY'
subscription_key = 'ADD_YOUR_SUBSCRIPTION_KEY'
api_url = 'ADD_API_URL'

try:
encrypted_result = encrypt_data(test_data, plugin_key_hex)
send_encrypted_data(encrypted_result, api_url, subscription_key)
except Exception as e:
print("An error occurred:", str(e))

C#

tip

Setup Instructions for C# Development Environment

  1. Install the "C#" Extension: Add the "C#" extension provided by Microsoft to your Visual Studio Code environment.

  2. Install the C# Dev Kit: Incorporate the C# Dev Kit extension into Visual Studio Code to enhance your C# development capabilities.

  3. Install the .NET Install Tool: Integrate the .NET Install Tool extension into Visual Studio Code for seamless management of .NET installations.

  4. Download and Install .NET SDK: Obtain the .NET Software Development Kit (SDK) from the official .NET website and install it on your system.

  5. Create a New C# File: Use the command dotnet new console -n EncryptionApp in your terminal to create a new C# file named "EncryptionApp" within your project directory.

  6. Add Newtonsoft.Json Package: Install the Newtonsoft.Json package, commonly used for JSON serialization and deserialization in C#, using the command dotnet add package Newtonsoft.Json.

Encryption Function

In your project directory, create a file named EncryptionService.cs.

using System;
using System.IO;
using System.Security.Cryptography;
using Newtonsoft.Json;

public class EncryptionService
{
public static string EncryptData(object data, string pluginKeyHex)
{
byte[] pluginKey = HexStringToByteArray(pluginKeyHex);
if (pluginKey.Length != 32)
{
throw new Exception("Key must be 32 bytes for AES-256-CBC");
}
using (Aes aes = Aes.Create())
{
aes.Key = pluginKey;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.GenerateIV();
byte[] iv = aes.IV;
using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, iv))
using (MemoryStream ms = new MemoryStream())
{
ms.Write(iv, 0, iv.Length);
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(JsonConvert.SerializeObject(data));
}
return Convert.ToBase64String(ms.ToArray());
}
}
}

private static byte[] HexStringToByteArray(string hex)
{
int numberChars = hex.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
}

Sending encrypted data to the server

In your project directory, create a file named DataSenderService.cs.

using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class DataSenderService
{
public static async Task SendEncryptedData(string encryptedData, string apiUrl, string subscriptionKey)
{
var payload = new
{
encryptedData = encryptedData,
subscriptionKey = subscriptionKey
};
using (HttpClient client = new HttpClient())
{
StringContent content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(apiUrl, content);
}
}
}

Main code using both the function

Create a file called program.cs in your project directory.

using System;
using System.Threading.Tasks;

public class Program
{
public static async Task Main(string[] args)
{
var testData = new
{
email = "ADD_EMAIL",
governmentId = "ADD_GOVERNMENT_ID",
governmentIdType = "ADD_GOVERNMENT_TYPE_ID",
jobObject = new
{
jobSkills = new[] { 'ADD_JOB_SKILLS' },
jobRole = "ADD_JOB_ROLE",
employmentType = "ADD_EMPLOYMENT_TYPE",
ghostedReasonByCompany = "ADD_GHOSTING_REASON"
}
};

string pluginKeyHex = "ADD_YOUR_PLUGIN_KEY";
string subscriptionKey = "ADD_YOUR__SUBSCRIPTION_KEY";
string apiUrl = "ADD_API_URL";

string encryptedResult = EncryptionService.EncryptData(testData, pluginKeyHex);
await DataSenderService.SendEncryptedData(encryptedResult, apiUrl, subscriptionKey);
}
}

PHP

tip

Running the Provided PHP Code

To execute the provided PHP code successfully, follow these steps:

  1. Install GuzzleHttp Client:
    • Use Composer to install the GuzzleHttp Client package by running the following command in your terminal:
      composer require guzzlehttp/guzzle
    • Ensure Composer is installed on your system. If not, download and install it from getcomposer.org.

Encryption Function

Create a file named EncryptionService.php with the following content:

function encryptData($data, $pluginKeyHex) {
$pluginKey = hex2bin($pluginKeyHex);
if (strlen($pluginKey) != 32) {
throw new Exception("Key must be 32 bytes for AES-256-CBC");
}

$iv = random_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$jsonData = json_encode($data);
$paddedData = pkcs7_pad($jsonData, 16);

$encryptedData = openssl_encrypt($paddedData, 'aes-256-cbc', $pluginKey, OPENSSL_RAW_DATA, $iv);
$encryptedBlob = base64_encode($iv . $encryptedData);
return $encryptedBlob;
}

function pkcs7_pad($data, $blocksize) {
$pad = $blocksize - (strlen($data) % $blocksize);
return $data . str_repeat(chr($pad), $pad);
}

Sending encrypted data to the server

Create a file named DataSenderService.php with the following content:

use GuzzleHttp\Client;

function sendEncryptedData($encryptedData, $apiUrl, $subscriptionKey) {
$payload = [
'encryptedData' => $encryptedData,
'subscriptionKey' => $subscriptionKey
];

$client = new Client();
$response = $client->post($apiUrl, [
'json' => $payload,
'headers' => ['Content-Type' => 'application/json']
]);

$body = $response->getBody();
$responseData = json_decode($body, true);
if (isset($responseData['message'])) {
echo "API Message: " . $responseData['message'] . "\n";
} else {
echo "No 'message' field in response.\n";
}
}

Main code using both the function

Create a file named Main.php that will use the services from the previous steps:

require 'vendor/autoload.php';
require 'EncryptionService.php';
require 'DataSenderService.php';


$testData = [
'email' => 'ADD_EMAIL',
'governmentId' => 'ADD_GOVERNMENT_ID',
'governmentIdType' => 'ADD_GOVERNMENT_TYPE_ID',
'jobObject' => [
'jobSkills' => ['ADD_JOBSKILLS'],
'jobRole' => 'ADD_JOBROLE',
'employmentType' => 'ADD_EMPLOYMENT_TYPE',
'ghostedReasonByCompany' => 'ADD_REASON_FOR_GHOSTING'
]
];

$pluginKeyHex = 'ADD_YOUR_PLUGIN_KEY'; // Ensure your key is 32 bytes in hex format
$subscriptionKey = 'ADD_YOUR_SUBSCRIPTION_KEY'; // Replace with your subscription key
$apiUrl = 'ADD_API_URL'; // Replace with your API URL

try {
$encryptedResult = encryptData($testData, $pluginKeyHex);
sendEncryptedData($encryptedResult, $apiUrl, $subscriptionKey);
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage() . "\n";
}

JAVA

tip

Adding Dependencies for Running Java Code

To run the provided Java code successfully, you need to include the following dependencies in your project:

  1. Gson:

    • Gson is a Java library used for JSON serialization and deserialization.

    • Add the Gson dependency to your project by including the following Maven or Gradle configuration:

      <!-- Maven -->
      <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.8</version>
      </dependency>
      // Gradle
      implementation 'com.google.code.gson:gson:2.8.8'
  2. Apache HttpClient:

    • Apache HttpClient is a library used for making HTTP requests in Java.

    • Include the Apache HttpClient dependency in your project with the following Maven or Gradle configuration:

      <!-- Maven -->
      <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.13</version>
      </dependency>
      // Gradle
      implementation 'org.apache.httpcomponents:httpclient:4.5.13'
  3. Bouncy Castle Provider:

    • Bouncy Castle is a cryptography library that provides algorithms and utilities for encryption and decryption.

    • Add the Bouncy Castle Provider dependency to your project using the following Maven or Gradle configuration:

      <!-- Maven -->
      <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-jdk15on</artifactId>
      <version>1.68</version>
      </dependency>
      // Gradle
      implementation 'org.bouncycastle:bcprov-jdk15on:1.68'

Once you've added these dependencies to your project configuration, your Java project will have access to the required packages for running the provided code.

Encryption Function

Create a class named EncryptionUtils.java , this utility class will handle all encryption-related operations.

package com.example;

import com.google.gson.Gson;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;

public class EncryptionUtils {
static {
Security.addProvider(new BouncyCastleProvider());
}

public static String encryptData(TestData data, String pluginKeyHex) throws Exception {
byte[] pluginKey = hexStringToByteArray(pluginKeyHex);
byte[] iv = new byte[16];
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
SecretKeySpec keySpec = new SecretKeySpec(pluginKey, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
Gson gson = new Gson();
byte[] encryptedBytes = cipher.doFinal(gson.toJson(data).getBytes(StandardCharsets.UTF_8));
byte[] ivAndEncryptedData = Arrays.copyOf(iv, iv.length + encryptedBytes.length);
System.arraycopy(encryptedBytes, 0, ivAndEncryptedData, iv.length, encryptedBytes.length);
return Base64.encodeBase64String(ivAndEncryptedData);
}

private static byte[] hexStringToByteArray(String s) {
byte[] data = new byte[s.length() / 2];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) ((Character.digit(s.charAt(i*2), 16) << 4) + Character.digit(s.charAt(i*2 + 1), 16));
}
return data;
}
}

Sending encrypted data to the server

Create a class named DataSender.java, this class will be responsible for sending encrypted data to the server.

package com.example;

import com.google.gson.Gson;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.nio.charset.StandardCharsets;

public class DataSender {
public static void sendEncryptedData(String encryptedData, String apiUrl, String subscriptionKey) throws Exception {
Payload payload = new Payload();
payload.encryptedData = encryptedData;
payload.subscriptionKey = subscriptionKey;
Gson gson = new Gson();
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(apiUrl);
httpPost.setEntity(new StringEntity(gson.toJson(payload), StandardCharsets.UTF_8));
httpPost.setHeader("Content-type", "application/json");
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
// Simplified response handling
System.out.println("Response: " + response.getStatusLine().getStatusCode());
}
}
}

Main code using both the function

Create a main class named App.java, this class will use the utilities to encrypt the data and send it.

public class App {
public static void main(String[] args) {
try {
TestData testData = new TestData();
testData.email = "ADD_EMAIL";
testData.governmentId = "ADD_GOVERNMENT_ID";
testData.governmentIdType = "ADD_GOVERNMENT_ID_TYPE";

JobObject jobObject = new JobObject();
jobObject.jobSkills = new String[]{"ADD_JOB_SKILLS"};
jobObject.jobRole = "ADD_JOB_ROLE";
jobObject.employmentType = "ADD_EMPLOYMENT_TYPE";
jobObject.ghostedReasonByCompany = "ADD_GHOSTING_REASON";

testData.jobObject = jobObject;

String pluginKeyHex = "ADD_YOUR_PLUGIN_KEY";
String subscriptionKey = "ADD_YOUR_SUBSCRIPTION_KEY";
String apiUrl = "ADD_API_URL";

String encryptedResult = EncryptionUtils.encryptData(testData, pluginKeyHex);

DataSender.sendEncryptedData(encryptedResult, apiUrl, subscriptionKey);
} catch (Exception e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}

GO

tip

Setting up Go Development Environment

To begin developing with Go programming language, follow these steps:

  1. Install Go Programming Language:

    • Download and install the Go programming language from the official website: golang.org.
  2. Install Go Extension in Visual Studio Code:

    • Open Visual Studio Code.
    • Navigate to the Extensions view by clicking on the square icon on the sidebar or pressing Ctrl+Shift+X.
    • Search for "Go" in the Extensions Marketplace.
    • Click on the "Install" button next to the "Go" extension provided by Go Team at Google.

These steps will ensure that you have the necessary tools and extensions to start developing with Go in Visual Studio Code.

Encryption Function

Create a file named EncryptionService.go, this file will handle all encryption-related operations..

package main

import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
)

// Encrypts data using AES-256-CBC, given a hex-encoded key
func encryptData(data interface{}, pluginKeyHex string) (string, error) {
pluginKey, err := hex.DecodeString(pluginKeyHex)
if err != nil {
return "", err
}

if len(pluginKey) != 32 {
return "", fmt.Errorf("key must be 32 bytes for AES-256-CBC")
}

iv := make([]byte, aes.BlockSize)
if _, err := rand.Read(iv); err != nil {
return "", err
}

block, err := aes.NewCipher(pluginKey)
if err != nil {
return "", err
}

stream := cipher.NewCBCEncrypter(block, iv)
plainText, err := json.Marshal(data)
if err != nil {
return "", err
}

paddedText := pkcs7Pad(plainText, aes.BlockSize)
cipherText := make([]byte, len(paddedText))
stream.CryptBlocks(cipherText, paddedText)

encryptedBlob := append(iv, cipherText...)
return base64.StdEncoding.EncodeToString(encryptedBlob), nil
}

func pkcs7Pad(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}

Sending encrypted data to the server

Create a class named DataSender.go, this file will be responsible for sending encrypted data to the server.

package main

import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
)

type Payload struct {
EncryptedData string `json:"encryptedData"`
SubscriptionKey string `json:"subscriptionKey"`
}

// Sends encrypted data to the server
func sendEncryptedData(encryptedData, apiUrl, subscriptionKey string) error {
payload := Payload{
EncryptedData: encryptedData,
SubscriptionKey: subscriptionKey,
}

jsonPayload, err := json.Marshal(payload)
if err != nil {
return err
}

resp, err := http.Post(apiUrl, "application/json", bytes.NewBuffer(jsonPayload))
if err != nil {
return err
}
defer resp.Body.Close()

_, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}

return nil
}

Main code using both the function

Create a main file named Main.go, this file will use the utilities to encrypt the data and send it..

package main

import "fmt"

func main() {
testData := TestData{
Email: "ADD_EMAIL",
GovernmentID: "ADD_GOVERNMENT_ID",
GovernmentIDType: "ADD_GOVERNMENT_TYPE_ID",
JobObject: JobObject{
JobSkills: []string{"ADD_JOB_SKILLS"},
JobRole: "ADD_JOB_ROLE",
EmploymentType: "ADD_EMPLOYMENT_TYPE",
GhostedReasonByCompany: "ADD_GHOSTING_REASON",
},
}

pluginKeyHex := "ADD_YOUR_PLUGIN_KEY"
subscriptionKey := "ADD_YOUR_SUBSCRIPTION_KEY"
apiUrl := "API_URL"

encryptedResult, err := encryptData(testData, pluginKeyHex)
if err != nil {
fmt.Println("An error occurred during encryption:", err)
return
}

if err := sendEncryptedData(encryptedResult, apiUrl, subscriptionKey); err != nil {
fmt.Println("An error occurred while sending data:", err)
}
}

These examples demonstrate how to send the encrypted 'Report Ghosting' data to the server using the subscription key for authentication. The key aspects are constructing the correct HTTP headers, formatting the request body appropriately, and handling the server's response to ensure the data has been transmitted successfully.